package com.hc.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hc.mall.product.entity.CategoryBrandRelationEntity;
import com.hc.mall.product.service.CategoryBrandRelationService;
import com.hc.mall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.utils.PageUtils;
import com.hc.common.utils.Query;

import com.hc.mall.product.dao.CategoryDao;
import com.hc.mall.product.entity.CategoryEntity;
import com.hc.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> level1List = categoryEntities.stream().filter((entity) -> {
            return entity.getParentCid() == 0;
        }).map((item) -> {
            item.setChildren(getChildrens(item, categoryEntities));
            return item;
        }).sorted((a, b) -> {
            return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());
        return level1List;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查菜单能否删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) { //查询分类的完整路径
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return (Long[]) paths.toArray(new Long[paths.size()]);
    }


//    @Caching(evict = {
//            @CacheEvict(value = {"category"} , key = "'getLevel1Category'"),
//            @CacheEvict(value = {"category"} , key = "'getCatelogJson'")
//            }
//    )
    @CacheEvict(value = {"category"},allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    /**
     * 1.默认行为
     *      1.1 缓存中有，方法不调用
     *      1.2 key默认自动生成
     *      1.3 缓存的值使用jdk序列化机制结果
     *      1.4 永不过期
     * 2.自定义
     *      2.1 指定key: 设置key 支持SpEL表达式
     *      2.2 指定存活时间：配置文件中修改ttl
     *      2.3 将数据保存为json：自定义缓存管理器
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.method.name") //代表方法结果需要缓存
    @Override
    public List<CategoryEntity> getLevel1Category() {
        List<CategoryEntity> selectList = baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, 0));
        return selectList;
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Category = getParent_Cid(selectList, 0l);
        Map<String, List<Catelog2Vo>> map = level1Category.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            List<CategoryEntity> category2EntityList = getParent_Cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (category2EntityList != null) {
                catelog2VoList = category2EntityList.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    List<CategoryEntity> category3EntityList = getParent_Cid(selectList, item.getCatId());
                    if (category3EntityList != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = category3EntityList.stream().map(cate -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), cate.getCatId().toString(), cate.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        return map;
    }
    //TODO 问题产生 OutOfDirectMemoryError
    //1.springboot2 默认使用lettuce操作redis客户端，其使用netty进行网络通信
    //2.lettuce的bug导致netty产生该问题
    //3.升级lettuce客户端/切换使用jedis
//    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) { //缓存中没有
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedissonLock();
            return catelogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock(); //加锁
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock(); //解锁
        }
        return dataFromDb;
    }
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //1.占分布式锁，去redis加锁，并设置过期时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if(lock){
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            }finally {
                String script = "if redis.call('get', KEY[1]) == ARGV[1] then return redis.call('del' , KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<>(script, Integer.class),Arrays.asList("lock"),uuid);
            }
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                redisTemplate.delete("lock");
//            }
            return dataFromDb;
        }else{
            try {
                Thread.sleep(200);
            }catch (Exception e){

            }
            return getCatelogJsonFromDbWithRedisLock();
        }
    }

    public Map<String, List<Catelog2Vo>> getDataFromDb(){
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            return JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Category = getParent_Cid(selectList, 0l);
        Map<String, List<Catelog2Vo>> map = level1Category.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            List<CategoryEntity> category2EntityList = getParent_Cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (category2EntityList != null) {
                catelog2VoList = category2EntityList.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    List<CategoryEntity> category3EntityList = getParent_Cid(selectList, item.getCatId());
                    if (category3EntityList != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = category3EntityList.stream().map(cate -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), cate.getCatId().toString(), cate.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        String string = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catelogJson", string); //查数据库并进行缓存
        return map;
    }
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {
        synchronized (this) {
            Map<String, List<Catelog2Vo>> map = getDataFromDb();
            return map;
        }
    }

    private List<CategoryEntity> getParent_Cid(List<CategoryEntity> list, Long parentCid) {
        return list.stream().filter(i -> i.getParentCid() == parentCid).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    //递归获取当前菜单的所有子菜单
    public List<CategoryEntity> getChildrens(CategoryEntity current, List<CategoryEntity> originList) {
        List<CategoryEntity> result = originList.stream().filter(item -> {
            return item.getParentCid().equals(current.getCatId());
        }).map(item -> {
            item.setChildren(getChildrens(item, originList));
            return item;
        }).sorted((a, b) -> {
            return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());
        return result;
    }
}
